package leetcode.editor.cn;

import java.util.LinkedList;
import java.util.Queue;

public class BinaryTreeFactory {
    /**
     * 根据传入的数组生成对应的二叉树
     *
     * @param arr
     * @return
     */
    public static TreeNode generateBinaryTreeFromArray(Integer[] arr) {
        if (arr.length == 0) {
            return null;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode root = new TreeNode(arr[0]);
        Queue<Integer> indexQueue = new LinkedList<>(); // 存放节点对应的数组的索引值
        queue.offer(root);
        indexQueue.offer(0);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            Integer index = indexQueue.poll();
            int leftIndex = 2 * index + 1;
            int rightIndex = 2 * index + 2;
            // 确保索引不会超出数组长度
            if (leftIndex < arr.length) {
                if (arr[leftIndex] == null) {
                    // 节点为null的时候不需要加入队列中
                    node.left = null;
                } else {
                    node.left = new TreeNode(arr[leftIndex]);
                    queue.offer(node.left);
                    indexQueue.offer(leftIndex);
                }
            }
            if (rightIndex < arr.length) {
                if (arr[rightIndex] == null) {
                    node.right = null;
                } else {
                    node.right = new TreeNode(arr[rightIndex]);
                    queue.offer(node.right);
                    indexQueue.offer(rightIndex);
                }
            }
        }
        return root;
    }

    public static void main(String[] args) {
        Integer[] arr = {1, 2, null, 3};
        TreeNode root = generateBinaryTreeFromArray(arr);
        System.out.println(root.val);
    }
}
